package com.ssy.lingxi.platform.manage.serviceimpl.content;

import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.constant.ShelfEnum;
import com.ssy.lingxi.platform.manage.entity.content.MemberAdvert;
import com.ssy.lingxi.platform.manage.entity.content.QMemberAdvert;
import com.ssy.lingxi.platform.manage.model.request.common.CommonIdRequest;
import com.ssy.lingxi.platform.manage.model.request.common.CommonStatusRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MemberAdvertPageRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MemberAdvertQueryRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MemberAdvertRequest;
import com.ssy.lingxi.platform.manage.repository.MemberAdvertRepository;
import com.ssy.lingxi.platform.manage.service.content.IMemberAdvertService;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 内容能力 - 广告管理
 * @author hsl
 * @version 2.0.0
 * @date 22/03/11 11:17
 */
@Service
public class MemberAdvertServiceImpl implements IMemberAdvertService {

    @Resource
    private MemberAdvertRepository memberAdvertRepository;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public Wrapper<PageData<MemberAdvert>> page(MemberAdvertPageRequest request, UserLoginCacheDTO sysUser) {
        QMemberAdvert qMemberAdvert = QMemberAdvert.memberAdvert;
        JPAQuery<MemberAdvert> jpaQuery = jpaQueryFactory.select(qMemberAdvert).from(qMemberAdvert);
        jpaQuery.where(qMemberAdvert.createMemberId.eq(sysUser.getMemberId())
                .and(qMemberAdvert.createMemberRoleId.eq(sysUser.getMemberRoleId())));
        if (StringUtils.isNotBlank(request.getTitle())) {
            jpaQuery.where(qMemberAdvert.title.contains(request.getTitle()));
        }
        if (request.getStatus() != null) {
            jpaQuery.where(qMemberAdvert.status.eq(request.getStatus()));
        }
        if (request.getStartTime() != null) {
            jpaQuery.where(qMemberAdvert.createTime.goe(request.getStartTime()));
        }
        if (request.getEndTime() != null) {
            jpaQuery.where(qMemberAdvert.createTime.loe(request.getEndTime()));
        }
        long totalCount = jpaQuery.fetchCount();
        List<MemberAdvert> list = jpaQuery.orderBy(qMemberAdvert.createTime.desc()).limit(request.getPageSize()).offset((long) (request.getCurrent() - 1) * request.getPageSize()).fetch();

        return Wrapper.success(new PageData<>(totalCount, list));
    }

    @Override
    public Wrapper<MemberAdvert> get(CommonIdRequest request) {
        MemberAdvert memberAdvert = memberAdvertRepository.findById(request.getId()).orElse(null);
        if (memberAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        return Wrapper.success(memberAdvert);
    }

    @Override
    @Transactional
    public Wrapper<Void> add(MemberAdvertRequest request, UserLoginCacheDTO sysUser) {
        if (memberAdvertRepository.existsBySortAndColumnTypeAndCreateMemberIdAndCreateMemberRoleId(request.getSort(), request.getColumnType(),sysUser.getMemberId(),sysUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }
        MemberAdvert memberAdvert = new MemberAdvert();
        BeanUtils.copyProperties(request, memberAdvert);
        memberAdvert.setCreateMemberId(sysUser.getMemberId());
        memberAdvert.setCreateMemberRoleId(sysUser.getMemberRoleId());
        memberAdvertRepository.saveAndFlush(memberAdvert);
        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> update(MemberAdvertRequest request, UserLoginCacheDTO sysUser) {
        MemberAdvert existsMemberAdvert = memberAdvertRepository.findBySortAndColumnTypeAndCreateMemberIdAndCreateMemberRoleId(request.getSort(), request.getColumnType(),sysUser.getMemberId(),sysUser.getMemberRoleId());
        if (existsMemberAdvert != null && existsMemberAdvert.getId() - request.getId() != 0) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }

        MemberAdvert memberAdvert = memberAdvertRepository.findById(request.getId()).orElse(null);
        if (memberAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (memberAdvert.getStatus().equals(ShelfEnum.ON_SHELF.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        BeanUtils.copyProperties(request, memberAdvert);
        memberAdvertRepository.saveAndFlush(memberAdvert);
        return Wrapper.success();    }

    @Override
    @Transactional
    public Wrapper<Void> updateStatus(CommonStatusRequest request, UserLoginCacheDTO sysUser) {
        MemberAdvert memberAdvert = memberAdvertRepository.findById(request.getId()).orElse(null);

        if (memberAdvert == null||!sysUser.getMemberId().equals(memberAdvert.getCreateMemberId())) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        memberAdvert.setStatus(request.getShelfStatus());
        memberAdvertRepository.saveAndFlush(memberAdvert);
        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> delete(CommonIdRequest request, UserLoginCacheDTO sysUser) {
        MemberAdvert memberAdvert = memberAdvertRepository.findById(request.getId()).orElse(null);
        if (memberAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (memberAdvert.getStatus().equals(ShelfEnum.ON_SHELF.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        memberAdvertRepository.delete(memberAdvert);
        return Wrapper.success();    }

    @Override
    public Wrapper<List<MemberAdvert>> findAllByColumnType(MemberAdvertQueryRequest request) {
        List<MemberAdvert> list = memberAdvertRepository.findAllByStatusAndColumnTypeAndCreateMemberIdAndCreateMemberRoleId(ShelfEnum.ON_SHELF.getCode(),request.getColumnType() ,request.getMemberId(),request.getMemberRoleId(), Sort.by(Sort.Direction.ASC, "sort"));
        return Wrapper.success(list);    }
}
